package com.practice.concurrency;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchMain {

	public static void main(String[] args) {
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch end = new CountDownLatch(10);
		final ExecutorService service = Executors.newFixedThreadPool(10);

		for (int i = 0; i < 10; i++) {
			service.submit(new CountDownLatchCommand(i, begin, end));
		}
		System.out.println("Game start");
		begin.countDown();
		try {
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Game over");
		service.shutdown();
	}
}

class CountDownLatchCommand implements Runnable {
	private int id;
	private CountDownLatch begin;
	private CountDownLatch end;

	public CountDownLatchCommand(int id, CountDownLatch begin,
			CountDownLatch end) {
		this.id = id;
		this.begin = begin;
		this.end = end;
	}

	@Override
	public void run() {
		try {
			begin.await();
			Thread.sleep((long) (Math.random() * 10000));
			System.out.println("[" + this.id + "] arrived");
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		} finally {
			end.countDown();
		}
	}
};
